'use client';

import { useEffect, useState } from 'react';
import { PokemonType } from '../types/pokemon';
import { getPokemonTypes } from '../services/pokemonService';

interface TypeFilterProps {
  selectedTypes: string[];
  onTypeSelect: (typeId: string) => void;
  onTypeDeselect: (typeId: string) => void;
}

export default function TypeFilter({ selectedTypes, onTypeSelect, onTypeDeselect }: TypeFilterProps) {
  const [types, setTypes] = useState<PokemonType[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  
  useEffect(() => {
    const fetchTypes = async () => {
      try {
        setIsLoading(true);
        const response = await getPokemonTypes();
        setTypes(response.results);
        setError(null);
      } catch (err) {
        setError('Failed to load Pokemon types');
        console.error(err);
      } finally {
        setIsLoading(false);
      }
    };
    
    fetchTypes().then(r => console.log('类型加载完成...'));
  }, []);
  
  // 提取类型ID从URL
  const getTypeIdFromUrl = (url: string): string => {
    const matches = url.match(/\/(\d+)\/$/);
    return matches ? matches[1] : '';
  };
  
  // 处理类型点击
  const handleTypeClick = (typeId: string) => {
    if (selectedTypes.includes(typeId)) {
      onTypeDeselect(typeId);
    } else {
      onTypeSelect(typeId);
    }
  };
  
  return (
    <div className="flex mb-3">
      <text className="text-xl font-bold">Types：</text>
      
      {isLoading ? (
        <div className="flex justify-center">
          <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-gray-900"></div>
        </div>
      ) : error ? (
        <div className="text-red-500">{error}</div>
      ) : (
        <div className="flex flex-wrap gap-2">
          {types.map((type) => {
            const typeId = getTypeIdFromUrl(type.url);
            const isSelected = selectedTypes.includes(typeId);
            return (
              <button key={typeId} onClick={() => handleTypeClick(typeId)}
                      className={`px-3 py-1 rounded-full text-sm
                      ${isSelected ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-800'}`}>
                {type.name}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}
